package com.yufu.geyan;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.g.gysdk.EloginActivityParam;
import com.g.gysdk.GYManager;
import com.g.gysdk.GYResponse;
import com.g.gysdk.GyCallBack;
import com.g.gysdk.GyPreloginResult;
import com.getcapacitor.JSObject;
import com.getcapacitor.PermissionState;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;
import com.getcapacitor.annotation.Permission;
import com.getcapacitor.annotation.PermissionCallback;

import org.json.JSONException;

@CapacitorPlugin(
  name = "GeYan",
  permissions = @Permission(
    strings = {
      Manifest.permission.READ_EXTERNAL_STORAGE,
      Manifest.permission.WRITE_EXTERNAL_STORAGE,
      Manifest.permission.READ_PHONE_STATE
    },
    alias = "default"
  )
)
public class GeYanPlugin extends Plugin {
  private int preLoginTimeout = 8000;
  private final GeYan implementation = new GeYan();
  private final GYManager gyManager = GYManager.getInstance();
  private PreLoginResult preLoginResult = null;

  private static AppCompatActivity staticContext;

  @Override
  public void load() {
    super.load();
    staticContext = getActivity();
  }

  TextView numberView;
  TextView sloganView;
  Button loginButton;
  CheckBox privacyCheckbox;
  TextView privacyView;
  boolean isaaa = false;

  public void aaaaa() {
    if (isaaa) {
      return;
    }
    isaaa = true;

    RelativeLayout relative = new RelativeLayout(staticContext);
    relative.setBackgroundColor(Color.YELLOW);

    ViewGroup.LayoutParams aaa = getActivity().getWindow().getDecorView().getLayoutParams();
    System.out.println("ffffffffffffffffffffffffff333313");
    numberView = new TextView(staticContext);
    sloganView = new TextView(staticContext);
    loginButton = new Button(staticContext);
    privacyCheckbox = new CheckBox(staticContext);
    privacyView = new TextView(staticContext);

    ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    relative.addView(privacyView);
    relative.addView(privacyCheckbox);
//    staticContext.addContentView(numberView, aaa);
//    staticContext.addContentView(sloganView, aaa);
////    staticContext.addContentView(loginButton, aaa);
//    staticContext.addContentView(privacyCheckbox, aaa);
//    staticContext.addContentView(privacyView, aaa);


    privacyCheckbox.setChecked(true);


    sloganView.setText("");
    sloganView.append("15500000000155000000001550000000015500000000");
//    loginButton.setText("--点击登录--");
//    loginButton.setTextColor(Color.parseColor("#ff4400"));

    privacyView.setHeight(1);
    privacyCheckbox.setHeight(1);
    privacyCheckbox.setMinHeight(1);
//    privacyView.setLineSpacing(8.0F, 1.0F);
//    privacyView.setMovementMethod(LinkMovementMethod.getInstance());

    GyPreloginResult preLoginResult = GYManager.getInstance().getPreLoginResult();

    privacyView.setText("");
    privacyView.append("登录即认可");
    privacyView.append(generateSpan(preLoginResult.getPrivacyName(), preLoginResult.getPrivacyUrl()));
    privacyView.append("、");
    privacyView.append(generateSpan("自定义协议1", "https://www.getui.com/about"));
    privacyView.append("、");
    privacyView.append(generateSpan("自定义协议2", "https://www.getui.com/verification"));
    privacyView.append("和");
    privacyView.append(generateSpan("自定义协议3", "https://docs.getui.com/geyan/"));
    privacyView.append("并使⽤用本机号码登录");

    EloginActivityParam param = new EloginActivityParam()
      .setActivity(staticContext)
      // 号码栏，必填项
      .setNumberTextview(numberView)
      // 运营商品牌露出，必填项
      .setSloganTextview(sloganView)
      // 运营商品牌露出，必填项
      .setLoginButton(loginButton)
      // 隐私确认框，必填项
      .setPrivacyCheckbox(privacyCheckbox)
      // 隐私协议，必填项
      .setPrivacyTextview(privacyView)
      .setUiErrorListener(new EloginActivityParam.UIErrorListener() {
        @Override
        public void onError(String s) {
          System.out.println("-----------------=-=-" + s);
        }
      }).setLoginOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          System.out.println("一键登录按钮 onLoginClick:");
        }
      });
    gyManager.eAccountLogin(param, 5000, new GyCallBack() {
      @Override
      public void onSuccess(GYResponse gyResponse) {
        System.out.println("eAccountLogin success -----" + gyResponse);
      }

      @Override
      public void onFailed(GYResponse gyResponse) {
        System.out.println("eAccountLogin failed -----" + gyResponse);
      }
    });

    privacyCheckbox.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        System.out.println("点击了隐私协议checkBox，当前状态：" + ((CheckBox) v).isChecked());
      }
    });
  }

  private SpannableString generateSpan(final String name, final String url) {
    SpannableString spannableString = new SpannableString(name);
    spannableString.setSpan(new ClickableSpan() {
      public void onClick(View view) {
        System.out.println("点击了隐私协议：" + name + "  " + url);
      }

      public void updateDrawState(TextPaint ds) {
        try {
          ds.setColor(0xFF3973FF);
          ds.setUnderlineText(false);
        } catch (Throwable t) {
          t.printStackTrace();
        }
      }
    }, 0, name.length(), 33);
    return spannableString;
  }

  /**
   * 获取个验证版本号
   */
  @PluginMethod
  public void version(PluginCall call) {
    JSObject ret = new JSObject();
    ret.put("version", gyManager.getVersion());
    call.resolve(ret);
  }


  /**
   * 初始化SDK
   */
  @PluginMethod
  public void init(PluginCall call) {
    if (getPermissionState("default") == PermissionState.GRANTED) {
      initSdk(call);
    } else {
      this.requestPermissionForAlias("default", call, "onPermissionInitCallback");
    }
  }

  @PermissionCallback
  public void onPermissionInitCallback(PluginCall call) {
    if (getPermissionState("default") == PermissionState.GRANTED) {
      initSdk(call);
    } else {
      call.reject("Permission is required to take a default");
    }
  }


  private void initSdk(PluginCall call) {
    GYManager.getInstance().init(staticContext, new GyCallBack() {
      @Override
      public void onSuccess(GYResponse gyResponse) {
        call.resolve();
      }

      @Override
      public void onFailed(GYResponse gyResponse) {
        call.reject("init onFailed response:" + gyResponse);
      }
    });
    preLogin(call);
  }

  /**
   * 设置渠道
   */
  @PluginMethod
  public void setChannel(PluginCall call) {
    String channel = call.getString("channel");
    gyManager.setChannel(channel);
    call.resolve();
  }

  /**
   * 预登录
   */
  @PluginMethod
  public void preLogin(PluginCall call) {
    Integer timeout = call.getInt("timeout", preLoginTimeout);
    if (timeout != null && timeout != preLoginTimeout) {
      preLoginTimeout = timeout;
    }
    preLogin(call, preLoginTimeout);
  }

  @PluginMethod
  public void login(PluginCall call) {
    call.reject("未完成");
//    getActivity().runOnUiThread(new Runnable() {
//      @Override
//      public void run() {
//        privacyCheckbox.setChecked(true);
//        loginButton.performClick();
//      }
//    });
  }

  public void preLogin(PluginCall call, int timeout) {
    gyManager.ePreLogin(timeout, new GyCallBack() {
      @Override
      public void onSuccess(GYResponse gyResponse) {
        preLoginResult = new PreLoginResult(gyResponse.getMsg());
//        aaaaa();
        call.resolve(preLoginResult.getData());
      }

      @Override
      public void onFailed(GYResponse gyResponse) {
        String errorCode = "";
        String errorDesc = "";
        try {
          JSObject jsObject = new JSObject(gyResponse.getMsg());
          errorCode = jsObject.getString("errorCode");
          errorDesc = jsObject.getString("errorDesc");
        } catch (JSONException ignored) {

        }
        call.reject(errorDesc, errorCode);
      }
    });
  }

  /**
   * 判断预登录是否有效
   */
  @PluginMethod
  public void isPreLoginResultValid(PluginCall call) {
    JSObject ret = new JSObject();
    ret.put("is_valid", gyManager.isPreLoginResultValid());
    call.resolve(ret);
  }


  /**
   * 获取预登录信息
   */
  @PluginMethod
  public void getPreLoginResult(PluginCall call) {
    GyPreloginResult result = gyManager.getPreLoginResult();
    boolean isValid = result.isValid();
    JSObject ret = new JSObject();
    // 预登录是否有效
    ret.put("is_valid", isValid);
    // 预登录的运营商，CM 移动，CT 电信，CU 联通
    ret.put("operator", result.getOperator());
    // 运营商隐私协议标题，比如"中国移动认证服务条款"
    ret.put("privacy_name", result.getPrivacyName());
    // 运营商隐私协议地址
    ret.put("privacy_url", result.getPrivacyUrl());
    if (isValid && preLoginResult != null) {
      ret.put("expired_time", preLoginResult.getExpiredTime());
      ret.put("client_type", preLoginResult.getClientType());
      ret.put("operator_type", preLoginResult.getOperatorType());
      ret.put("process_id", preLoginResult.getProcessId());
      ret.put("number", preLoginResult.getNumber());
    }
    call.resolve(ret);
  }

}
